package com.google.jcss;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.digester.Digester;

public class CompresorServlet extends HttpServlet {
	private PageDef pageDef;

	public void init(ServletConfig servletConfig) throws ServletException {
		String config = servletConfig.getInitParameter("config");
		if (config == null) {
			config = "jcss-config.xml";
		}
		try {
			Digester digester = new Digester();
			digester.setValidating(false);

			digester.addObjectCreate("configuration", Configuration.class);
			digester.addSetProperties("configuration");
			digester.addCallMethod("configuration/debug", "setDebug", 0);

			digester.addObjectCreate("configuration/page_def", PageDef.class);
			digester.addSetNext("configuration/page_def", "setPage_def");

			digester.addObjectCreate("configuration/page_def/page", Page.class);
			digester.addSetProperties("configuration/page_def/page");
			digester.addSetNext("configuration/page_def/page", "addPage");

			digester.addObjectCreate("configuration/page_def/page/resource",
					Resource.class);
			digester.addSetProperties("configuration/page_def/page/resource");
			digester.addSetNext("configuration/page_def/page/resource",
					"addResource");

			File input = new File(servletConfig.getServletContext()
					.getRealPath(config));
			Configuration conf = (Configuration) digester.parse(input);

			setPageDef(conf.getPage_def());
			pageDef.setDebug(conf.isDebug());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String typeResource = null;
		String url = request.getPathInfo();
		System.out.println("jscss: url del recurso pedido --> " + url);
		String resource = url.substring(url.indexOf('/') + 1);
		System.out.println("jscss: recurso --> " + resource);

		if (resource.endsWith(".css")) {
			response.setContentType("text/css");
			typeResource = Resource.TYPE_CSS;

		} else if (resource.endsWith(".js")) {
			response.setContentType("text/javascript");
			typeResource = Resource.TYPE_JAVASCRIPT;
		}

		System.out.println("jscss: recurso del tipo --> " + typeResource);

		//System.out.println(pageDef.getPage(resource).getName());
		pageDef.setContext(request.getSession().getServletContext());
		pageDef.process(response.getOutputStream(), resource, typeResource);
		if (pageDef.isDebug()) {
			response.addHeader("Content-Encoding", "gzip");
		}
		response.getOutputStream().flush();

	}

	public PageDef getPageDef() {
		return pageDef;
	}

	public void setPageDef(PageDef pages) {
		this.pageDef = pages;
	}

}
